package org.base.common.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.base.common.annotation.Pass;
import org.base.common.annotation.RequiredPerm;
import org.base.common.fs.FileSystem;
import org.base.common.pojo.FileInfo;
import org.base.sys.constant.SysConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@Api(value = "统一文件上传", tags = "文件上传")
@RestController
@RequestMapping(value = "/file", method = {RequestMethod.POST})
@Validated
@Slf4j
public class FileController {

    @Autowired
    private FileSystem fileSystem;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传", tags = "文件上传")
    @PostMapping("/upload")
    @RequiredPerm(value = SysConstant.LOGIN, editable = false)
    public FileInfo upload(@RequestParam("file") MultipartFile file) throws IOException {
        return fileSystem.upload(file);
    }

    @GetMapping("/{year}/{month}/{fileName}")
    @RequiredPerm(value = SysConstant.ANON, editable = false)
    public void file(@PathVariable(value = "year") String year, @PathVariable(value = "month") String month, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try (final InputStream inputStream = fileSystem.getFileInputStream("/" + year + "/" + month, request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1));
             final ServletOutputStream outputStream = response.getOutputStream()) {
            IOUtils.copy(inputStream, outputStream);
        }
    }
}
